package logic

import (
	"context"
	"cp/cache"
	"cp/cprpc/cprpc"
	"cp/cprpc/internal/svc"
	"cp/models/mysql"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(in *cprpc.UpdatePasswordRequest) (*cprpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendCode"+in.Phone).Result()
	if result != in.SendCode {
		return nil, errors.New("验证码错误")
	}
	type findUser mysql.User
	mysql.DB.Debug().Where("phone=?", in.Phone).Find(&findUser{})
	if in.Password != in.NewPassword {
		return nil, errors.New("新密码与确认密码不一致")

	}

	var user = mysql.User{
		Phone:    in.Phone,
		Password: in.Password,
	}
	mysql.DB.Debug().Updates(&user)

	return &cprpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
